#include <string>
#include <iostream>

#include <signal.h>

#include "../commen/httplib.h"
#include "./oj_control.hpp"

ns_control::control* pctrl;

void recovery(int signo)
{
    pctrl->recovery_machines();
}

int main()
{
    signal(SIGQUIT, recovery);

    // 用户请求的服务器路由功能
    httplib::Server svr;
    ns_control::control ctrl;
    pctrl = &ctrl;

    // 获取所有的题目列表
    svr.Get("/all_questions", [&ctrl](const httplib::Request &request, httplib::Response &response) -> void
            { 
                //返回一个包含所有题目的html网页
                std::string html;
                ctrl.get_all_questions(&html);
                response.set_content(html, "text/html;charset=utf-8"); });

    // 用户要根据题目编号,获取题目的内容
    //\d+(正则表达式)匹配1个或更多连续的数字。这里的+是和*类似的元字符，不同的是*匹配重复任意次(可能是0次)，而+则匹配重复1次或更多次。
    // R"()", 原始字符串raw string,保持字符串内容的原貌，不用做相关的转义
    svr.Get(R"(/questions/(\d+))", [&ctrl](const httplib::Request &request, httplib::Response &response) -> void
            {
        std::string number = request.matches[1];
        std::string html;
        ctrl.get_one_question(atoi(number.c_str()), &html);
        response.set_content( html, "text/html;charset=utf-8"); });

    // 用户提交代码,使用我们的判题能力(1.每道题目的测试用例 2.compile_run)
    svr.Post(R"(/judge/(\d+))", [&ctrl](const httplib::Request &request, httplib::Response &response) -> void
            {
        std::string number = request.matches[1];
        std::string result_json;
        ctrl.judge(atoi(number.c_str()), request.body, &result_json);
        response.set_content(result_json, "application/json;charset=utf-8"); });

    svr.set_base_dir("./wwwroot");

    svr.listen("0.0.0.0", 8080);
    return 0;
}